package com.skyworth.utils;

import com.google.common.io.Files;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by skyworth on 2016/1/28.
 */
public class FileManager {

    public static boolean upload(MultipartFile file,String uploadFilePath){
        boolean ret = false;
        File uploadFile = new File(uploadFilePath);
        try {
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(uploadFile));
            stream.write(bytes);
            stream.close();
            ret = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

    public static String todayUploadFolder(String dir) {
        return FileManager.todayUploadFolderForKind(dir, "media");
    }

    public static String todayUploadFolderForKind(String dir, String kind){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        dir  += "/" + sdf.format(new Date());
        // make sure dir exist
        File theDir = new File(dir);

        if (!theDir.exists()) {
            try {
                theDir.mkdirs();
            } catch(SecurityException se) {
                //handle it
            }
        }

        return dir;
    }

    public static String uuidFilename(String filename) {
        UUID uuid = UUID.randomUUID();
        String ext = Files.getFileExtension(filename);

        return uuid.toString().replace("-", "") + "." + ext;
    }

    public static String getMDFromFile(String path) throws FileNotFoundException {
        File file = new File(path);
        String value = null;
        FileInputStream in = new FileInputStream(file);
        try {
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }

}
